<template>
  <div v-loading="loading" class="app-container">
    <scheduleHeader ref="scheduleHeader" :parent="currentObj" />
    <div style="padding-top:5px">
      <span style="padding-right:10px;">采购：
        <el-select v-model="params.buyerId" placeholder="请选择" size="mini" style="width: 150px;" clearable>
          <el-option v-for="item in buyerIds" :key="item" :label="item" :value="item" />
        </el-select>
      </span>
      <span style="padding-right:10px;">线上条码：
        <el-input v-model="params.onlineUpcNbr" size="mini" placeholder="请输入" style="width: 150px;" clearable />
      </span>
      <span>状态：
        <el-select v-model="params.dataStatus" placeholder="请选择" size="mini" style="width: 150px;" clearable>
          <template v-for="item in getSelector().dataStatusList">
            <el-option v-if="item.itemListShow" :key="item.value" :label="item.name" :value="item.value" />
          </template>
        </el-select>
        <el-button size="mini" type="primary" style="margin-bottom:5px;" round @click="toQuery">查询</el-button>
      </span>
      <!--<el-button size="mini" type="danger" style="float:right;margin-bottom:5px;margin-left:1px;" round @click="batchDelete">删除</el-button>-->
      <el-button size="mini" type="primary" style="float:right;margin-bottom:5px;margin-left:2px;" round @click="toAdd">新增</el-button>
      <el-button size="mini" type="primary" style="float:right;margin-bottom:5px;margin-left:2px;" round @click="toDownloadTemplate">下载模板</el-button>
      <el-button size="mini" type="primary" style="float:right;margin-bottom:5px;margin-left:2px;" round @click="toSubmit">提交</el-button>
      <el-button size="mini" type="primary" style="float:right;margin-bottom:5px;" round @click="toAnalysis">分析</el-button>
      <el-button size="mini" type="primary" style="float:right;margin-bottom:5px;" round @click="toValidate">校验</el-button>
      <el-button size="mini" type="primary" style="float:right;margin-bottom:5px;" round @click="toDownload">导出</el-button>
      <el-button size="mini" type="primary" style="float:right;margin-bottom:5px;" plain round @click="toUpload">导入</el-button>
      <el-table
        ref="rule3Table"
        :data="data"
        :row-key="getRowKeys"
        stripe
        size="small"
        border
        style="width: 100%;"
        :header-cell-style="{ height: '0px', padding: '0px' }"
        :row-style="{height: '0px'}"
        :cell-style="{padding: '0px'}"
        :height="tableHeight"
        @row-click="rowClick"
        @sort-change="sortChange"
        @selection-change="handleSelectionChange"
        @header-dragend="colChange"
      >
        <!--<el-table-column :show-overflow-tooltip="true" type="index" prop="index" label="序号" fixed="left" :width="colWidths.index" />-->
        <el-table-column :show-overflow-tooltip="true" label="部门" prop="deptNbr" :width="colWidths.deptNbr?colWidths.deptNbr:70" />
        <el-table-column :show-overflow-tooltip="true" label="品类" prop="cateId" :width="colWidths.cateId?colWidths.cateId:70" />
        <el-table-column :show-overflow-tooltip="true" label="采购ID" prop="buyerId" :width="colWidths.buyerId?colWidths.buyerId:100" />
        <el-table-column :show-overflow-tooltip="true" label="线上条码" prop="onlineUpcNbr" :width="colWidths.onlineUpcNbr?colWidths.onlineUpcNbr:130" />
        <el-table-column :show-overflow-tooltip="true" label="线上商品名称" prop="onlineItemName" :width="colWidths.onlineItemName?colWidths.onlineItemName:140" />
        <el-table-column :show-overflow-tooltip="true" label="促销开始日期" prop="promotionStartDate" sortable :width="colWidths.promotionStartDate ? colWidths.promotionStartDate : 135">
          <template slot-scope="scope">
            <span>{{ parseToString(scope.row.promotionStartDate, 'yyyy-MM-dd') }}</span>
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" label="促销结束日期" prop="promotionEndDate" sortable :width="colWidths.promotionEndDate ? colWidths.promotionEndDate : 135">
          <template slot-scope="scope">
            <span>{{ parseToString(scope.row.promotionEndDate, 'yyyy-MM-dd') }}</span>
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" label="门店A状态校验" prop="dataStatus" :width="colWidths.dataStatus ? colWidths.dataStatus : 135">
          <template slot-scope="scope">
            <el-link type="warning" size="mini" @click="toViewStoreList(scope.row)">
              <span style="font-size: 12px;">
                总数:{{ scope.row.countTotal !== null ? scope.row.countTotal : '-' }},
                被过滤数:{{ scope.row.countNonAStatus !== null ? scope.row.countNonAStatus : '-' }}
              </span>
            </el-link>
          </template>
        </el-table-column>
        <itemStatus ref="itemStatus" :parent="currentObj" />
        <el-table-column :show-overflow-tooltip="true" label="价格/满减力度" prop="promotionPrice" :width="colWidths.promotionPrice?colWidths.promotionPrice:120" />
        <el-table-column :show-overflow-tooltip="true" label="发送门店" prop="sendStore" :width="colWidths.sendStore?colWidths.sendStore:130" />
        <el-table-column :show-overflow-tooltip="true" label="不发送门店" prop="omitSendStore" :width="colWidths.omitSendStore?colWidths.omitSendStore:130" />
        <el-table-column :show-overflow-tooltip="true" label="限购数量" prop="buyLimited" :width="colWidths.buyLimited?colWidths.buyLimited:100" />
        <el-table-column v-if="showOptionType" :show-overflow-tooltip="true" label="操作类型" prop="optionType" :width="colWidths.optionType?colWidths.optionType:100">
          <template slot-scope="scope">
            <span>{{ showNameByValue(scope.row.optionType, getSelector().optionTypes) }}</span>
          </template>
        </el-table-column>
        <!--<el-table-column :show-overflow-tooltip="true" label="备注" prop="remark" :width="colWidths.remark?colWidths.remark:130" />-->
        <el-table-column :show-overflow-tooltip="true" label="最后更新人" sortable prop="updatedBy" :width="colWidths.updatedBy ? colWidths.updatedBy : 120" />
        <el-table-column :show-overflow-tooltip="true" label="更新时间" sortable prop="updatedTime" :width="colWidths.updatedTime ? colWidths.updatedTime : 135">
          <template slot-scope="scope">
            <span>{{ parseToString(new Date(scope.row.updatedTime), 'yyyy-MM-dd HH:mm:ss') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" prop="operation" align="left" fixed="right" width="195">
          <template slot-scope="scope">
            <list-operation :parent="currentObj" :phase="scope.row" />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <el-pagination
        :total="total"
        :current-page.sync="currentPage"
        style="margin-top: 8px;"
        layout="total, prev, pager, next, sizes"
        :page-size="size"
        @size-change="sizeChange"
        @current-change="pageChange"
      />
    </div>
    <edit ref="edit" :parent="currentObj" />
    <upload ref="upload" :parent="currentObj" />
    <download ref="download" :parent="currentObj" />
    <storeList ref="storeList" />
    <analysisList ref="analysisList" :parent="currentObj" />
  </div>
</template>
<script>
import listOperation from './list-operation'
import edit from './edit'
import upload from './upload'
import download from './download'
import scheduleHeader from './schedule-header'
import analysisList from '@/views/olm/analysis/analysis-list'
import itemStatus from '@/views/olm/part/itemStatus'
import storeList from '@/views/olm/item-list/store-list'
import initData from '@/api/olm/initData'
import { parseToString } from '@/utils/datefromat'
import { getSelector } from './js/edit.js'
import { deleteById, batchDelete, submit } from '@/api/olm/item-list'
import { Message } from 'element-ui'
import { showNameByValue } from '@/utils/selectUtil'
import { getBuyerIds } from '@/api/olm/buyer-ma'
import { validate } from '@/api/olm/validate'
import { doDownload } from '@/api/olm/download'

export default {
  components: { listOperation, edit, upload, download, scheduleHeader, itemStatus, storeList, analysisList },
  mixins: [initData],
  data() {
    return {
      loading: false,
      syncTime: [],
      ids: [],
      checkedRows: [],
      currentObj: this,
      tableHeight: window.innerHeight * 0.65,
      buyerIds: [],
      schedule: null
    }
  },
  computed: {
    showOptionType: function() {
      return this.schedule !== null &&
      this.schedule.scheduleGroup !== undefined &&
      this.schedule.scheduleGroup != null &&
      this.schedule.scheduleGroup === 2 // 临时选品
    }
  },
  watch: {
    data: {
      handler(n, o) {
        this.$nextTick(() => {
          this.$refs.rule3Table.doLayout()
        })
      }
    }
  },
  created() {
    this.$nextTick(() => {
      this.loadBuyerId()
    })
  },
  methods: {
    parseToString,
    getSelector,
    showNameByValue,
    toViewStoreList(row) {
      if (row) {
        // console.log(JSON.stringify(row))
        var storeList = this.$refs.storeList
        storeList.findUpcStoreInfo(row.id)
        storeList.itemName = row.onlineItemName
        storeList.dialog = true
      }
    },
    // 查询栏重置触发
    resetForm() {
      this.param = { }
    },
    // 列表多选框触发
    handleSelectionChange(val) {
      this.ids = []
      val.forEach(item => {
        this.ids.push(item.id)
      })
    },
    // 翻页选择row的key值
    getRowKeys(row) {
      return row.id
    },
    beforeInit() {
      this.url = process.env.VUE_APP_BASE_API3 + '/olmList/queryPageList'
      return true
    },
    rowClick(row) {
      this.$refs.rule3Table.clearSelection(this.multipleSelection)
      this.$refs.rule3Table.toggleRowSelection(row, true)
    },
    // 列表排序触发
    sortChange(val) {
      const sortCol = val.prop.replace(/([A-Z])/g, '_$1').toUpperCase()
      let sortType = ''
      if (val.order === 'descending') {
        sortType = ' DESC'
      } else if (val.order === 'ascending') {
        sortType = ' ASC'
      }
      this.param.sort = sortCol + sortType
      this.init()
    },
    loadBuyerId() { // 加载采购ID
      var _this = this
      getBuyerIds().then(res => {
        if (res) {
          _this.buyerIds = res.result
        }
      })
    },
    // 查询
    toQuery() {
      this.page = 0
      this.currentPage = 1
      this.init()
    },
    // 新增
    toAdd() {
      const edit = this.$refs.edit
      edit.title = '新增'
      edit.dialog = true
      edit.entity.scheduleId = this.$refs.scheduleHeader.schedule.id
      edit.scheduleSubject = this.$refs.scheduleHeader.schedule.scheduleSubject
      edit.schedule = this.$refs.scheduleHeader.schedule
      if (this.buyerIds !== null && this.buyerIds.length === 1) { // 只有一个默认选中
        edit.entity.buyerId = this.buyerIds[0]
      }
      edit.currentOperate = 'ADD'
      console.log('toadd')
    },
    // 修改
    toEdit(entity) {
      const edit = this.$refs.edit
      var json = JSON.stringify(entity)
      var copyEntity = JSON.parse(json)
      edit.entity = copyEntity
      edit.title = '修改'
      edit.currentOperate = 'EDIT'
      edit.scheduleSubject = this.$refs.scheduleHeader.schedule.scheduleSubject
      edit.schedule = this.$refs.scheduleHeader.schedule
      edit.dialog = true
      console.log('toEdit')
    },
    // 查看
    toView(entity) {
      const edit = this.$refs.edit
      var json = JSON.stringify(entity)
      var copyEntity = JSON.parse(json)
      edit.entity = copyEntity
      edit.title = '查看'
      edit.currentOperate = 'VIEW'
      edit.scheduleSubject = this.$refs.scheduleHeader.schedule.scheduleSubject
      edit.schedule = this.$refs.scheduleHeader.schedule
      edit.dialog = true
      console.log('toView')
      // console.log('toView:' + JSON.stringify(phase))
    },
    // 删除
    deleteById(row) {
      var _this = this
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteById(row.id).then(res => {
          Message({
            message: '删除成功',
            type: 'success',
            duration: 2 * 1000
          })
          _this.toQuery()
          _this.$refs.rule3Table.clearSelection(_this.multipleSelection)
        })
      })
    },
    // 批量删除
    batchDelete() {
      var _this = this
      if (this.ids.length <= 0) {
        Message({
          message: '请选择删除项!',
          type: 'warning',
          duration: 2 * 1000
        })
        return
      }
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        batchDelete(this.ids).then(res => {
          Message({
            message: '删除成功',
            type: 'success',
            duration: 2 * 1000
          })
          _this.toQuery()
          _this.$refs.rule3Table.clearSelection(_this.multipleSelection)
        })
      })
    },
    toUpload() { // 导入
      var upload = this.$refs.upload
      upload.entity.scheduleId = this.$refs.scheduleHeader.schedule.id
      if (this.params.buyerId) {
        upload.entity.buyerId = this.params.buyerId
      } else {
        if (this.buyerIds && this.buyerIds.length === 1) {
          upload.entity.buyerId = this.buyerIds[0]
        }
      }
      upload.entity.scheduleSubject = this.$refs.scheduleHeader.schedule.scheduleSubject
      upload.dialog = true
    },
    toDownload() { // 下载
      var download = this.$refs.download
      download.entity.scheduleId = this.$refs.scheduleHeader.schedule.id
      if (this.params.buyerId) {
        download.entity.buyerId = this.params.buyerId
      } else {
        if (this.buyerIds && this.buyerIds.length === 1) {
          download.entity.buyerId = this.buyerIds[0]
        }
      }
      download.dialog = true
    },
    toDownloadTemplate() { // 下载模板
      this.loading = true
      doDownload('/olm-excel/excel/exportOlmListData', { scheduleId: -1 }, '清单文件模板.xlsx').then(res => {
        this.loading = false
      }, err => {
        console.log(err)
        this.loading = false
      })
    },
    toValidate() { // 校验方法
      this.$confirm('是否校验?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.data === null || this.data === undefined || this.data.length === undefined || this.data.length <= 0) {
          Message({
            message: '无数据校验',
            type: 'warning',
            duration: 2 * 1000
          })
          return
        }
        var scheduleId = this.$refs.scheduleHeader.schedule.id
        var data = { scheduleId: scheduleId, buyerIds: this.buyerIds }
        this.loading = true
        console.log('toValidate:' + JSON.stringify(data))
        validate(data).then(res => {
          if (res) {
            Message({
              message: res.result,
              type: 'success',
              duration: 2 * 1000
            })
          }
          this.loading = false
        }, err => {
          console.log(err)
          this.loading = false
        })
      })
    },
    toSubmit() { // 提交
      var _this = this
      this.$confirm('确认提交?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var data = { buyerIds: _this.buyerIds, scheduleId: _this.$refs.scheduleHeader.schedule.id }
        _this.loading = true
        submit(data).then(res => {
          Message({
            message: '提交成功',
            type: 'success',
            duration: 2 * 1000
          })
          _this.toQuery()
          _this.$refs.rule3Table.clearSelection(_this.multipleSelection)
          _this.loading = false
        }, err => {
          console.log(err)
          _this.loading = false
        })
      })
    },
    toAnalysis() { // 按采购，档期分析
      console.log('toAnalysis')
      var analysisList = this.$refs.analysisList
      analysisList.schedules = this.$refs.scheduleHeader.schedules
      analysisList.schedule = this.$refs.scheduleHeader.schedule
      analysisList.totalUrl = '/queryListAnalysisData'
      analysisList.deptUrl = '/queryDeptListAnalysisInfo'
      analysisList.buyerIds = this.buyerIds
      analysisList.type = 1
      analysisList.oldEntity.buyerIds = this.buyerIds
      analysisList.dialog = true
    }
  }
}
</script>
